<?php

namespace App\Services;

use App\Common\Libs\Ali\Oss;
use App\Common\Libs\ArrayHelper;
use App\Common\Libs\IdBuilder;
use App\Common\Libs\Json;
use App\Consts\GlobalSalonConst;
use App\Consts\GlobalUploadConst;
use App\Models\Field\SalonField;
use App\Models\Field\UserField;
use App\Models\Select\SalonSelect;
use App\Models\Select\UserSelect;
use App\Models\SysSalon;

/**
 * Class SalonService
 * @package App\Services
 */
class SalonService extends BaseService
{
    private $_repository;
    private $_salon;

    public function __construct()
    {
        parent::__construct();
        $this->_repository = repository()->SalonRepository;
    }

    /**
     * 获取所有沙龙，无分页
     * @param $searchParams
     * @return array
     */
    public function getSalonList($searchParams)
    {
        $dataProvider = $this->_repository->getSalonList($searchParams);
        $pagination = $this->getPagination();
        $indexSalons = $dataProvider->getModels();

        // 根据salon_id得到分表
        $salonIdTable = IdBuilder::getSubTable(ArrayHelper::getColumn($indexSalons, 'salon_id'));

        // 沙龙
        $salons = [];
        foreach ($salonIdTable as $tableCount => $salonIdArr) {
            $models = $this->_repository->getSalonByTableCount($tableCount, $salonIdArr, SalonSelect::SELF_LIST);
            $salons = ArrayHelper::merge($salons, $models);
        }

        $list = $this->formatSalons($salons);

        return self::outputMoreList($dataProvider, $pagination, $list);
    }

    /**
     * 获取状态为【往期回顾】的沙龙列表，有分页
     * @param $searchParams
     * @return array
     */
    public function getReviewSalonList($searchParams)
    {
        $dataProvider = $this->_repository->getSalonList($searchParams);
        $pagination = $this->getPagination();
        $indexSalons = $dataProvider->getModels();

        // 根据salon_id得到分表
        $salonIdTable = IdBuilder::getSubTable(ArrayHelper::getColumn($indexSalons, 'salon_id'));

        // 沙龙
        $salons = [];
        foreach ($salonIdTable as $tableCount => $salonIdArr) {
            $models = $this->_repository->getSalonByTableCount($tableCount, $salonIdArr, SalonSelect::SELF_LIST);
            $salons = ArrayHelper::merge($salons, $models);
        }

        $list = $this->formatSalons($salons);

        $list = ArrayHelper::multisort($list, 'start_at', SORT_DESC);

        return self::outputMoreList($dataProvider, $pagination, $list);
    }

    private function formatSalons($salons)
    {
        // 用户
        $userIdArr = ArrayHelper::getColumn($salons, 'user_id');
        $users = repository()->UserRepository->getUserByUserIdArr($userIdArr);
        $users = ArrayHelper::index($users, 'user_id');

        $list = [];
        /**
         * @var SysSalon $salon
         */
        foreach ($salons as $salon) {
            $formatSalon = SalonField::format($salon, SalonField::getFormats());
            $formatSalon = ArrayHelper::merge($formatSalon, [
                'weight' => GlobalSalonConst::$weightMap[$formatSalon['status']],
                'user' => isset($users[$salon['user_id']]) ? UserField::format($users[$salon['user_id']], UserField::getFormats()) : (object)[],
            ]);
            $list[] = $formatSalon;
        }

        $list = ArrayHelper::multisort($list, ['weight', 'start_at'], [SORT_DESC, SORT_ASC]);
        $result = [];
        foreach ($list as $data) {
            $data = ArrayHelper::remove($data, 'weight');
            $result[] = $data;
        }

        return $result;
    }

    public function getStatusByTime($startTime, $endTime, $isReview)
    {
        if ($isReview == GlobalSalonConst::IS_REVIEW && $endTime < time()) {
            return GlobalSalonConst::STATUS_REVIEW;
        }

        if ($startTime < time()) {
            if ($endTime < time()) {
                return GlobalSalonConst::STATUS_ENDING;
            }

            return GlobalSalonConst::STATUS_STARTING;
        }

        return GlobalSalonConst::STATUS_START_IMMEDIATELY;
    }

    /**
     * 根据沙龙ID获取沙龙记录
     * @param $salonId
     * @param string $selectScene
     * @return bool|SysSalon
     */
    public function getSalonBySalonId($salonId, $selectScene = SalonSelect::SELF_DETAIL)
    {
        if (empty($this->_salon[$salonId])) {
            $salon = $this->_repository->getSalonBySalonId($salonId, $selectScene);
            if (!$salon) {
                return false;
            }
            $this->_salon[$salonId] = $salon;
        }

        return $this->_salon[$salonId];
    }

    /**
     * 获取沙龙其他信息
     * @param SysSalon $salon
     * @return array|bool
     */
    public function getSalonMoreFields($salon, $currentUserId)
    {
        $user = repository()->UserRepository->getUserByUserId($salon->user_id, UserSelect::SALON);
        if (!$user) {
            return false;
        }

        // 预告内容、回顾内容、报名须知读取静态资源文件
        $obj = Oss::getInstance(GlobalUploadConst::OBJECT_SALON_INFO)
            ->getObject($salon->salon_id . '.json');
        if (!$obj) {
            return false;
        }

        $salonInfo = Json::decode($obj, true);

        return [
            'user' => ArrayHelper::merge($user->commonFormat(UserField::SALON), [
                'attention_status' => service()->RelationshipService->getAttentionStatus($currentUserId, $user->user_id),
            ]),
            'advance' => $salonInfo['advance'],
            'review' => $salonInfo['review'],
            'apply_information' => $salonInfo['apply_information'],
        ];
    }
}
